package com.jh.fcsm.service.sys.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.OSSObject;
import com.jh.fcsm.beans.sys.SysFileInfo;
import com.jh.fcsm.common.exception.ServiceException;
import com.jh.fcsm.dao.sys.SysFileInfoMapper;
import com.jh.fcsm.enums.FileSource;
import com.jh.fcsm.util.io.FileUtil;
import com.jh.fcsm.util.security.Base64Converter;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * 阿里云存储文件
 *
 * @author szx
 */
@Service("aliyunFileServiceImpl")
public class AliyunFileServiceImpl extends AbstractFileService {
    public static final Logger logger = LoggerFactory.getLogger(AliyunFileServiceImpl.class);
    @Autowired
    private SysFileInfoMapper fileDao;
    @Autowired
    private OSS ossClient;
    @Value("${file.aliyun.bucketName}")
    private String bucketName;
    @Value("${file.aliyun.domain}")
    private String domain;
    @Value("${file.aliyun.savefolder}")
    private String savefolder;
    @Value("${file.aliyun.isserver}")
    private boolean isserver;
    @Override
    protected SysFileInfoMapper getFileDao() {
        return fileDao;
    }

    @Override
    protected FileSource fileSource() {
        return FileSource.ALIYUN;
    }

    @Override
    protected SysFileInfo uploadLocalFile(File file, SysFileInfo fileInfo) throws Exception {
        try (InputStream inputStream = new FileInputStream(file);) {
            String md5 = FileUtil.fileMd5(inputStream);
            int index = fileInfo.getName().lastIndexOf(".");
            // 文件扩展名
            String fileSuffix = fileInfo.getName().substring(index);
            ossClient.putObject(bucketName, savefolder + md5 + fileSuffix, inputStream);
            if(!isserver){
                fileInfo.setUrl(domain + savefolder + md5 + fileSuffix);
            }else{
                String keyBase64 = Base64Converter.encode(savefolder + md5 + fileSuffix);
                fileInfo.setUrl(domain + keyBase64);
            }
            fileInfo.setPath(savefolder + md5 + fileSuffix);
        }
        return null;
    }

    @Override
    protected void uploadFile(MultipartFile file, SysFileInfo fileInfo) throws Exception {
        String md5 = FileUtil.fileMd5(file.getInputStream());
        int index = fileInfo.getName().lastIndexOf(".");
        // 文件扩展名
        String fileSuffix = fileInfo.getName().substring(index);
        ossClient.putObject(bucketName, savefolder + md5 + fileSuffix, file.getInputStream());
        if(!isserver){
            fileInfo.setUrl(domain + savefolder + md5 + fileSuffix);
        }else{
            String keyBase64 = Base64Converter.encode(savefolder + md5 + fileSuffix);
            fileInfo.setUrl(domain + keyBase64);
        }
        fileInfo.setPath(savefolder + md5 + fileSuffix);
    }

    @Override
    protected boolean deleteFile(SysFileInfo fileInfo) {
        ossClient.deleteObject(bucketName, fileInfo.getPath());
        return true;
    }

    @Override
    public void down(String key, HttpServletResponse response) {
        if (StringUtils.isEmpty(key)) {
            throw new ServiceException("非法请求");
        }
        OSSObject ossObject = null;
        int buffer = 1024 * 10;
        byte[] data = new byte[buffer];
        int lastIn = key.lastIndexOf('/');
        String fileName = lastIn < 0 ? key : key.substring(lastIn);
        try {
            ossObject = ossClient.getObject(bucketName, key);
            InputStream inputStream = ossObject.getObjectContent();
            // 设置excel的文件名称
            response.setHeader("Content-disposition", "attachment; filename=" + fileName);
            response.setContentType("multipart/octet-stream");
            OutputStream out = response.getOutputStream();
            int read;
            while ((read = inputStream.read(data)) != -1) {
                out.write(data, 0, read);
            }
            out.flush();
            out.close();
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } finally {
            if (ossObject != null) {
                try {
                    ossObject.close();
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
        }
    }

    /**
     * @param file
     * @param fileInfo
     * @param markPath
     * @throws Exception 上传配置文件
     * @author szx
     */
    @Override
    protected void uploadFile(MultipartFile file, SysFileInfo fileInfo, String markPath) throws Exception {
        // 文件路径
        StringBuilder sb = new StringBuilder("/");
        if (!StringUtils.isEmpty(markPath)) {
            sb.append(markPath).append("/");
        }
        sb.append(fileInfo.getName());
        // 配置文件目录为blbConfig/
        ossClient.putObject(bucketName, savefolder + sb, file.getInputStream());
        fileInfo.setUrl(domain + savefolder + sb);
        fileInfo.setPath(savefolder + sb);
    }

    @Override
    public boolean copyFile(String source, String taraget) {
        // TODO Auto-generated method stub
        return false;
    }

//    /**
//     * 上传配置文件
//     *
//     * @param file
//     * @param path 路径
//     * @return
//     * @throws Exception
//     */
//    public SysFileInfo uploadConfigFile(MultipartFile file, String fileNme, String path) throws IOException {
//        SysFileInfo fileInfo = new SysFileInfo();
//        int index = fileNme.lastIndexOf(".");
//        // 文件扩展名
//        String fileSuffix = fileNme.substring(index);
//        ossClient.putObject(bucketName, savefolder + path + fileNme, file.getInputStream());
//        String keyBase64 = Base64Converter.encode(savefolder + path + fileNme);
//        fileInfo.setUrl(domain + keyBase64);
//        fileInfo.setPath(savefolder + path + fileSuffix);
//        return fileInfo;
//    }

}
